<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="searchForm" :model="searchForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="人员名称">
              <el-input
                v-model="searchForm.userName"
                placeholder="请输入人员名称"
              />
            </el-form-item>
          </el-col>
          <el-col :offset="12" :span="6" class="text-right">
            <el-button
              icon="iconfont iconxianxing_sousuo"
              type="primary"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              icon="iconfont iconxianxing_zhongzhi"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-col>
          <el-col :span="24" class="text-left">
            <el-button type="primary" @click="onAdd">
              新增人员
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table
        ref="table"
        :current-page="page"
        :header-data="tableHeader"
        :index="false"
        :loading="loading"
        :page-size="limit"
        :table-data="tableData"
        :total="total"
        class="data-table"
        style="width: 100%"
        border
        @now-page="handlePage"
        @now-size="handleSize"
        @table-sort="handleSort"
      />
    </el-main>
    <el-drawer
      :title="title"
      :visible.sync="drawerVisible"
      :wrapper-closable="false"
    >
      <div class="drawer-main">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="top"
          label-width="80px"
        >
          <el-form-item label="人员名称" prop="userName" required>
            <el-input v-model="form.userName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="人员类型" prop="role" required>
            <el-select v-model="form.role" placeholder="请输入">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门" prop="unitId" required>
            <el-select
              v-model="unitName"
              placeholder="请输入"
              value-key="unitId"
              @change="(val) => onChange(val, 'unitName', 'unitId')"
            >
              <el-option
                v-for="item in departList"
                :key="item.unitId"
                :label="item.unitName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="type !== 'look'" class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
          <el-button @click="onCancel"> 取消</el-button>
        </div>
      </div>
    </el-drawer>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getUsersList,
  postUserDel,
  postUserAdd,
  postUserUpdate,
  getDepartList,
  updatePass,
} from "./api";
import { parseTime } from "@/utils";

export default {
  name: "UserList",
  mixins: [addTable],
  data() {
    return {
      searchForm: {
        userName: "",
      },
      roleList: [
        { id: "1", name: "管理员" },
        { id: "2", name: "监督员" },
        { id: "3", name: "操作员" },
      ],
      departList: [],
      unitName: {},
      title: "",
      type: "look",
      tableHeader: [],
      personOptions: [],
      oneLoading: false,
      drawerVisible: false,
      form: {
        role: "2",
        userName: "",
        remark: "",
        unitName: "",
        unitId: null,
      },
      rules: {
        userName: [{ required: true, message: "姓名必填" }],
        unitId: [{ required: true, message: "部门必填" }],
        role: [{ required: true, message: "人员类型必填" }],
      },
    };
  },
  created() {
    this.tableHeader = [
      {
        prop: "userName",
        label: "人员名称",
        sortable: false,
        overflow: true,
        width: 180,
        align: "left",
      },
      {
        prop: "role",
        label: "人员类型",
        sortable: false,
        overflow: true,
        align: "left",
        render: (h, vm) => {
          const roleName = this.roleList.find((item) => item.id === vm.role);
          return <span>{roleName.name}</span>;
        },
      },
      {
        prop: "unitName",
        label: "所属部门",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "remark",
        label: "备注",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "createdTime",
        label: "创建时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = parseTime(vm.createdTime);
          return <span>{time}</span>;
        },
      },
      {
        width: 200,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          return [
            {
              text: "重置密码",
              type: "text",
              event: this.onRestPass,
            },
            {
              text: "编辑",
              type: "text",
              event: this.onEdit,
            },
            {
              text: "删除",
              type: "text",
              event: this.onDelete,
            },
          ];
        },
      },
    ];
    this.getDepartList();
    this.getTableData();
  },

  methods: {
    async onChange(val, type, id) {
      this.form[type] = val[type];
      this.form[id] = val[id];
    },
    async getDepartList() {
      const { data } = await getDepartList({
        page: 1,
        limit: 1000,
      });
      this.departList = data;
    },
    onRestPass(row) {
      this.$confirm("您确认要重置密吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updatePass({ userId: row.userId })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
          })
          .catch();
      });
    },
    onEdit(row) {
      this.unitName = {
        ...row,
      };
      this.form = {
        ...row,
      };
      console.log(this.form);
      this.type = "edit";
      this.title = "编辑人员";
      this.drawerVisible = true;
    },
    onAdd() {
      this.form = {};
      this.type = "add";
      this.title = "新增人员";
      this.drawerVisible = true;
    },
    onDelete(row) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        postUserDel({ userId: row.userId })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.getTableData();
          })
          .catch();
      });
    },
    getTableData() {
      this.loading = true;
      this.getTableParams();
      getUsersList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data, pageInfo } = res;
          setTimeout(() => {
            this.loading = false;
            this.tableData = data;
            this.total = pageInfo.total;
          }, 500);
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.userId
            ? postUserUpdate(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              })
            : postUserAdd(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onCancel() {
      this.drawerVisible = false;
      this.$refs.form.resetFields();
    },
  },
};
</script>
